package org.changs.nav;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

import org.changs.aplug.ActivityManager;
import org.changs.aplug.utils.AppUtils;
import org.changs.nav.ui.nav.MainActivity;
import org.changs.s3.common.tools.AppTools;
import org.changs.s3.common.tools.NavTools;
import org.changs.servlet.IOUtils;

import dagger.android.DaggerBroadcastReceiver;
import timber.log.Timber;

/**
 * Created by yincs on 2017/9/4.
 */

public class NavReceive extends DaggerBroadcastReceiver {

    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        this.mContext = context;
        final String action = intent.getAction();
        Timber.d("action = " + action);
        if (IOUtils.Action.SYM_MAP_DATA.equals(action)) {
            intent.setComponent(new ComponentName(context, NavService.class));
            context.startService(intent);
        } else if (NavTools.ACTION_S3_NAV.equals(action)) {
            handleNav(intent);
        }
    }

    private void handleNav(Intent intent) {
        final int type = intent.getIntExtra(NavTools.EXTRA_TYPE, -1);
        if (type == -1) return;
        if (type == NavTools.TYPE_NAV_OPEN) {//打开导航
            if (AppUtils.isAppForeground(mContext)) {
                Timber.d("接收到打开导航命令，但app已经处于前台，不处理该命令");
                return;
            }
            Activity activity = ActivityManager.getInstance().getCurrentActivity();
            if (activity == null) {
                AppTools.launcher(mContext, mContext.getPackageName());
            } else {
                activity.startActivity(new Intent(activity, activity.getClass()));
            }
        } else if (type == NavTools.TYPE_NAV_CLOSE) {//关闭导航
            ActivityManager.getInstance().finishAllActivity();
        } else {//其他控制指令
//            MapNavActivity navActivity = ActivityManager.getInstance().findActivity(MapNavActivity.class);
//            if (navActivity != null) {
//                navActivity.finish();
//            }
            Context context = ActivityManager.getInstance().getCurrentActivity();
            Intent mainIntent = new Intent();
            mainIntent.setComponent(new ComponentName(mContext, MainActivity.class));
            if (context == null) {
                context = mContext;
                mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            }
            mainIntent.replaceExtras(intent);
            context.startActivity(mainIntent);
        }
    }


}
